package com.iven.xie.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.iven.xie.entity.DbConfig;
import com.iven.xie.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xiezhendong
 * @date 2021/7/22
 */
@Service
@Slf4j
public class ConfigServiceImpl implements ConfigService {

    @Value("${dbManager.default.config:}")
    private String dbDefaultConfig;

    private Map<String, DbConfig> deFaultConfigMap = Maps.newHashMap();

    private Map<String, DbConfig> getDeFaultConfigMap() {
        if (Objects.nonNull(dbDefaultConfig)) {
            try {
                List<DbConfig> dbConfigList = JSONArray.parseArray(dbDefaultConfig, DbConfig.class);
                deFaultConfigMap = dbConfigList.stream().collect(Collectors.toMap(u -> u.getConnName(), u -> u));
            } catch (Exception e) {
                log.error("加载默认数据库配置报错");
            }
        }
        return deFaultConfigMap;
    }

    @Override
    public Map<String, DbConfig> getDeFaultConfig() {
        return this.getDeFaultConfigMap();
    }


}
